package com.system.coupon.controller;


import com.system.common.resp.CommonResp;
import com.system.common.resp.PageResp;
import com.system.coupon.enums.CouponCategoryEnum;
import com.system.coupon.model.R;
import com.system.coupon.req.CouponQueryReq;
import com.system.coupon.service.CouponService;

import com.system.coupon.vo.CouponVO;
import org.redisson.api.RLock;

import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 二当家小D
 * @since 2021-02-07
 */

@RestController
@RequestMapping
public class CouponController {


    @Autowired
    private CouponService couponService;

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("page_coupon")
    public CommonResp<PageResp<CouponVO>> pageCouponList(
         @Valid CouponQueryReq req
    ) {
        PageResp<CouponVO> couponVOPageResp = couponService.pageCouponActivity(req);
        return new CommonResp<>(couponVOPageResp);
    }

    /**
     * 领取优惠券
     *
     * @param couponId
     * @return
     */
    @GetMapping("/add/promotion/{coupon_id}")
    public R addPromotionCoupon( @PathVariable("coupon_id") long couponId) {
        //分布式锁
        String lockKey = "lock:coupon:" + couponId + ":" +"3";
        RLock rLock = redissonClient.getLock(lockKey);
        //多个线程进入，会阻塞等待释放锁，默认30秒，然后有watch dog自动续期
        rLock.lock();
        try {
            couponService.addCoupon(couponId, CouponCategoryEnum.PROMOTION);
            return R.ok("领取优惠卷成功！");
        } finally {
            rLock.unlock();
            System.out.println("解锁成功");
        }
    }
}

